package com.example.sport.service.impl;

import com.example.sport.domain.User;
import com.example.sport.mapper.UserMapper;
import com.example.sport.service.UserService;
import com.example.sport.utils.MD5Utils;
import com.example.sport.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;


@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public User findUserByName(String username) {
        return userMapper.findUserByName(username);
    }

    @Override
    public void register(String username, String password, String role, String collegeId, String name) {
        //MD5加密
        String md5password = MD5Utils.getMD5String(password);
        User tuser = new User();
        tuser.setUsername(username);
        tuser.setPassword(md5password);
        tuser.setRole(role);
        if (!Objects.equals(collegeId, "")){
            tuser.setCollegeId(Integer.valueOf(collegeId));
        }
        tuser.setName(name);
        userMapper.insert(tuser);
    }

    @Override
    public void update(User tuser) {
        User newTuser = new User();
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        newTuser.setId(id);
        if (tuser.getName() != null) {
            newTuser.setCollegeId(tuser.getCollegeId());
        }
        if (tuser.getName() != null) {
            newTuser.setName(tuser.getName());
        }
        userMapper.updateById(newTuser);
    }


    @Override
    public void updatePwd(String newPwd) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        User tuser = new User();
        tuser.setId(id);
        tuser.setPassword(MD5Utils.getMD5String(newPwd));
        userMapper.updateById(tuser);
    }

    @Override
    public List<User> getAllUser(User user) {
        return userMapper.selectAllUser(user);
    }

    @Override
    public User findUserById(Integer userId) {
        return userMapper.findUserById(userId);
    }
}
